package com.choosefine.it.basedata.service;

import com.choosefine.it.basedata.dao.WorkTypeMapper;
import com.choosefine.it.basedata.model.WorkType;
import com.choosefine.it.basedata.model.vo.WorkTypeFindVO;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("workTypeService")
public class WorkTypeService {

	@Resource
	private WorkTypeMapper workTypeMapper;
	
	public int deleteByPrimaryKey(Integer id) {
		int num = 0;
		Map<String,Object> map = new HashMap<>();
		WorkType deleteWorkType = workTypeMapper.selectByPrimaryKey(id);
		map.put("sortNum", id);
		map.put("superId", deleteWorkType.getSuperId());
		WorkType deleteWorkTypeUp = workTypeMapper.selectWorkTypeBySortNum(map);
		if(null != deleteWorkTypeUp){
			deleteWorkTypeUp.setSortNum(deleteWorkType.getSortNum());
			num += workTypeMapper.updateByPrimaryKeySelective(deleteWorkTypeUp);
		}
		num += workTypeMapper.deleteByPrimaryKey(id);
		return num;
	}

	public WorkType findByPrimaryKey(Integer id) {
		
		return workTypeMapper.selectByPrimaryKey(id);
	}

	public List<WorkType> selectAll() {
		
		return workTypeMapper.selectAll();
	}

	public int insert(WorkType record) throws BusinessException {
		Map<String,Object> checkMap = new HashMap<>();
		checkMap.put("name", record.getName());
		checkMap.put("superId", record.getSuperId());
		int count = workTypeMapper.checkWorkTypeInsert(checkMap);
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		int num = 0;
		Map<String,Object> map = new HashMap<>();
		Map<String,Object> mapNew = new HashMap<>();
		map.put("sortNum", 0);
		map.put("superId", record.getSuperId());
		mapNew.put("superId", record.getSuperId());
		WorkType lastWorkType = workTypeMapper.selectWorkTypeBySortNum(map);
		if(null != lastWorkType){
			record.setSortNum(-1);
			num += workTypeMapper.insertSelective(record);
			mapNew.put("sortNum", -1);
			record = workTypeMapper.selectWorkTypeBySortNum(mapNew);
			lastWorkType.setSortNum(record.getId());
			record.setSortNum(0);
			num += workTypeMapper.updateByPrimaryKeySelective(record);
			num += workTypeMapper.updateByPrimaryKeySelective(lastWorkType);
		}else{
			record.setSortNum(0);
			num += workTypeMapper.insertSelective(record);
		}
		return num;
	}

	public int update(WorkType record) throws BusinessException {
		Map<String,Object> checkMap = new HashMap<>();
		checkMap.put("name", record.getName());
		checkMap.put("superId", record.getSuperId());
		int count = workTypeMapper.checkWorkTypeInsert(checkMap);
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		return workTypeMapper.updateByPrimaryKeySelective(record);
	}

	public PageInfo<WorkType> selectWorkTypeListByFather(Integer fatherId,Integer pageNum,Integer pageSize) throws BusinessException
	{
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		List<WorkType> getList = workTypeMapper.getWorkTypeListByFather(fatherId);
		if(getList.size()==0){
			return new PageInfo<WorkType>();
		}
		List<WorkType> returnList = WorkTypeOrder(getList);
		int start = (pageNum-1) * pageSize;
		if (start > returnList.size()) {
			return new PageInfo<WorkType>();
		}
		int end = pageNum * pageSize;
		end = end > returnList.size()?returnList.size()-1:end;
		returnList = returnList.subList(start , end);
		return new PageInfo<WorkType>(returnList);
	}
	public List<WorkType> selectWorkTypeListByFather(Integer fatherId) throws BusinessException
	{
		List<WorkType> getList = workTypeMapper.getWorkTypeListByFather(fatherId);
		if(getList.size()==0){
			return new ArrayList<WorkType>();
		}
		List<WorkType> returnList = WorkTypeOrder(getList);
		return returnList;
	}

	public List<WorkType> getWorkTypeListByFather(Integer fatherId)
	{

		return workTypeMapper.getWorkTypeListByFather(fatherId);
	}
	
	public PageInfo<WorkType> findAllByPage(Map<String, Object> t,
			Integer pageNo, Integer pageSize) {
		List<WorkType> returnList = workTypeMapper.selectAll();
		pageNo = pageNo == null?1:pageNo;
		pageSize = pageSize == null?10:pageSize;
		PageHelper.startPage(pageNo,pageSize);  //startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		return new PageInfo<WorkType>(returnList);
	}
	
	public PageInfo<WorkType> getWorkTypeListByName(Map<String, Object> map,Integer pageNum,Integer pageSize)
	{
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<WorkType>(workTypeMapper.getWorkTypeListByName(map));
	}
	public List<WorkType> getWorkTypeListByName(Map<String, Object> map)
	{
		return workTypeMapper.getWorkTypeListByName(map);
	}
	public int WorkTypeOrderUp(Integer fromId,Integer toId){
		int num = 0;
		Map<String,Object> map = new HashMap<>();
		map.put("sortNum", fromId);
		Map<String,Object> mapNew = new HashMap<>();
		mapNew.put("sortNum", toId);
		WorkType fromWorkType = null;
		WorkType fromWorkTypeUp = null;
		WorkType toWorkTypeUp = null;
		fromWorkType = workTypeMapper.selectByPrimaryKey(fromId);
		map.put("superId", fromWorkType.getSuperId());
		mapNew.put("superId", fromWorkType.getSuperId());
		fromWorkTypeUp = workTypeMapper.selectWorkTypeBySortNum(map);
		toWorkTypeUp = workTypeMapper.selectWorkTypeBySortNum(mapNew);
		if(toWorkTypeUp == null){
			fromWorkTypeUp.setSortNum(fromWorkType.getSortNum());
			fromWorkType.setSortNum(toId);
		}else{
			fromWorkTypeUp.setSortNum(fromWorkType.getSortNum());
			fromWorkType.setSortNum(toId);
			toWorkTypeUp.setSortNum(fromId);
		}
		if(null != toWorkTypeUp){
			num += workTypeMapper.updateByPrimaryKeySelective(toWorkTypeUp);
		}
		num += workTypeMapper.updateByPrimaryKeySelective(fromWorkType);
		num += workTypeMapper.updateByPrimaryKeySelective(fromWorkTypeUp);
		return num;
	}
	public int WorkTypeOrderDown(Integer fromId,Integer toId){
		int num = 0;
		Map<String,Object> map = new HashMap<>();
		map.put("sortNum", fromId);
		WorkType fromWorkType = null;
		WorkType fromWorkTypeUp = null;
		WorkType toWorkType = null;
		fromWorkType = workTypeMapper.selectByPrimaryKey(fromId);
		map.put("superId", fromWorkType.getSuperId());
		fromWorkTypeUp = workTypeMapper.selectWorkTypeBySortNum(map);
		toWorkType = workTypeMapper.selectByPrimaryKey(toId);
		if(fromWorkTypeUp == null){
			fromWorkType.setSortNum(toWorkType.getSortNum());
			toWorkType.setSortNum(fromId);
		}else{
			fromWorkTypeUp.setSortNum(fromWorkType.getSortNum());
			fromWorkType.setSortNum(toWorkType.getSortNum());
			toWorkType.setSortNum(fromId);
		}
		if(null != fromWorkTypeUp){
			num += workTypeMapper.updateByPrimaryKeySelective(fromWorkTypeUp);
		}
		num += workTypeMapper.updateByPrimaryKeySelective(fromWorkType);
		num += workTypeMapper.updateByPrimaryKeySelective(toWorkType);
		return num;
	}
	/**
	 * 用于返回根据 sortNum 排序后的，列表
	 *  juchengyang 2017年2月16日
	 * @throws BusinessException 
	 */
	public List<WorkType> WorkTypeOrder(List<WorkType> getList) throws BusinessException{
		checkList(getList);
		int size = getList.size();
		List<WorkType> returnList = new ArrayList<>();
		for(WorkType temp:getList){
			//最后一位 sortNum 为0
			if(0 == temp.getSortNum()){
				returnList.add(temp);
			}
		}
		WorkType tempWorkType = returnList.get(0);
		while(returnList.size()<size){
			for(int i = 0; i<size; i++){
				if(tempWorkType.getId().equals(getList.get(i).getSortNum())){
					returnList.add(getList.get(i));
					tempWorkType = getList.get(i);
				}
			}
		}
		for(int i=0; i<size/2; i++){
			WorkType tempProjecType = returnList.get(i);
			returnList.set(i, returnList.get(size-i-1));
			returnList.set(size-i-1, tempProjecType);
		}
		return returnList; 
	}
	/**
	 * @Description：查询所有一级工种
	 * @Author：chenjian
	 * @Create Date：2017年2月17日
	 * @param：
	 * @return：
	 */
	public List<WorkTypeFindVO> findWorkTypeList(){ 
		return workTypeMapper.findWorkTypeList();
	}
	/**
	 * @Description：根据一级工种id查询所有二级工种
	 * @Author：chenjian
	 * @Create Date：2017年2月17日
	 * @param：
	 * @return：
	 */
	public List<WorkTypeFindVO> findWorkTypeListBySuperId(Integer superId){
		return workTypeMapper.findWorkTypeListBySuperId(superId);
	}
	/*
	 * 数据校验
	 */
	public void checkList (List<WorkType> list) throws BusinessException{
    	Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
        Map<Integer, Integer> nextMap = new HashMap<Integer, Integer>();
        for( WorkType n: list){
        	if (nextMap.containsKey(n.getSortNum())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：next重复");
            }
        	if (n.getSortNum().equals(n.getId())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：指向自己");
            }
        	keyMap.put(n.getId(), n.getSortNum());
            nextMap.put(n.getSortNum(), 0);
        }
        if(!nextMap.containsKey(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("数据出错：不存在0（最后一位标识）");
        }
        for (WorkType n : list) {
            Integer next = keyMap.get(n.getId());
            if (next.equals(0)) {
            	if(!nextMap.containsKey(n.getId()) && nextMap.size()>1){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("没有指向最后一位的");
            	}
            	if(nextMap.get(next).equals(1)){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("数据出错，最后一位不唯一");
            	}else{
            		nextMap.put(next, 1);
            	}
            	
            } else {
            	if(keyMap.containsKey(next)){
	            	if(nextMap.get(next).equals(1)){
	            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//	            		logger.info("数据出错，"+next+"重复");
	            	}else{
	            		nextMap.put(next, 1);
	            	}
            	}else{
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info(next+" 没有对应的 id");
            	}
            }

        }
        if(nextMap.containsValue(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("next 有无效值");
        }
    }
}
